package component;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import service.UserService;
import service.impl.UserServiceImplTest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: ZhouBert
 * @date: 2020/9/17
 * @description:	测试：使用 InstantiationAwareBeanPostProcessor 拓展点进行 JDK 动态代理增强！
 */
public class TestJDKProxyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		/// 不能用 myTestBean ，因为 jdk 代理是通过实现接口的方式，而 MyTestBean 不是接口；除非通过 cglib 进行继承的方式！
//		if (beanName.equals("myTestBean")) {
//			MyTestBean myTestBean = new MyTestBean();
//			MyTestBean userDao = (MyTestBean) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{MyTestBean.class}, new InvocationHandler() {
//				@Override
//				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//					System.out.println("我是JDK动态代理的");
//					method.invoke(myTestBean);
//					return null;
//				}
//			});
//			return userDao;
//		}

		if(beanName.equals("userService")){
			//用 UserServiceImplTest 替代了 配置类中的 UserServiceImpl
			UserService userDaoimpl=new UserServiceImplTest();
			UserService userDao= (UserService) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					System.out.println("我是JDK动态代理的");
					method.invoke(userDaoimpl);
					return userDaoimpl;
				}
			});
			return userDao;
		}

		// 什么都不做，顺其自然！
		return null;
	}
}
